﻿using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace PerfAssist.Common.Editor
{
    public class PAAssetUtil
    {
        // http://answers.unity3d.com/questions/486545/getting-all-assets-of-the-specified-type.html
        public static List<T> FindByType<T>() where T : Object
        {
            var showProgressBar = false;

            string t;
            if (typeof(T) == typeof(GameObject))
            {
                t = "t:Prefab";
                showProgressBar = true;
            }
            else
            {
                t = string.Format("t:{0}", typeof(T).ToString().Replace("UnityEngine.", ""));
            }

            var assets = new List<T>();
            var guids = AssetDatabase.FindAssets(t);
            for (var i = 0; i < guids.Length; i++)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);
                if (showProgressBar)
                    EditorUtility.DisplayCancelableProgressBar("FindByType",
                        string.Format("Loading {0} ({1}/{2})", assetPath, i, guids.Length),
                        i / (float) guids.Length);

                var asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
                if (asset != null) assets.Add(asset);
            }

            if (showProgressBar)
                EditorUtility.ClearProgressBar();
            return assets;
        }
    }
}